package com.venta.autopartes.user.add;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.config.entities.Parameterizable;
import com.venta.autopartes.dao.UserDAO;
import com.venta.autopartes.user.User;
import com.venta.autopartes.user.UserPrivilage;
import com.venta.autopartes.utils.Constants;
import com.venta.autopartes.utils.DataCatalog;
import com.venta.autopartes.utils.FormatUtility;
import com.venta.autopartes.utils.SessionFactory;
import com.venta.autopartes.utils.SessionValidator;
import com.venta.autopartes.utils.TransferFileFTP;

public class GoStartAddUserAction extends ActionSupport implements SessionAware {
	
	private Map session;
	
	private List<File> upload = new ArrayList<File>();
    private List<String> uploadContentType = new ArrayList<String>();
    private List<String> uploadFileName = new ArrayList<String>();
    
    private HttpServletRequest servletRequest;
   // private Map<String, String> params;
    private String register; 
	
	private User userForm;
	
	public String goStartAddUser(){
		String result=INPUT;
		//System.out.println(session.get("usersListSearch"));
		SessionFactory.removePreviosSessionData();
		
		System.out.println("Register Type: " + register);
		if(register!=null && register.equalsIgnoreCase(Constants.FOREIGN_USER)&&session.get(Constants.USER_LOGGED)==null){
			System.out.println("Getting data catalogs for vehicles, locations...");
			if(session.get(Constants.DATA_CATALOG)==null){
				DataCatalog dataCatalog = new DataCatalog();
				session.put(Constants.DATA_CATALOG, dataCatalog);
			}
			session.put(Constants.SESSION_TYPE, Constants.FOREIGN_USER);
			session.put(Constants.REGISTER, register);
			result=SUCCESS;
		}else{
			if(!SessionValidator.isValidSession(session)){
				return SessionValidator.INVALID_SESSION;
			}
			session.put(Constants.REGISTER, register);
			result=SUCCESS;
			//session.put(Constants.USER_SEARCH_RESULT, Constants.NULL);
			
			
		}
		
		return result;
	}
	
	public String addNewUser(){
		
		if(!SessionValidator.isValidSession(session)){
			return SessionValidator.INVALID_SESSION;
		}
		
		String sessionType=(String)session.get(Constants.SESSION_TYPE);

		User userSelected=this.userForm;
		
		DataCatalog dataCatalog=(DataCatalog)session.get(Constants.DATA_CATALOG);
		dataCatalog.getAddressNamesByCountryId(this.userForm.getAddress());
		dataCatalog.getGenderByGenderId(this.userForm.getGender());
		dataCatalog.getUserPrivilageByUserPrivilageId(this.userForm.getUserPrivilage());
		dataCatalog.getBranchDepartmentByBranchDepartmentId(this.userForm.getUserBranch().getBranchDepartment());
		dataCatalog.getBranchUserRoleByBranchUserRoleId(this.userForm.getUserBranch().getBranchUserRole());
		dataCatalog.getQuestionByQuestionId(this.userForm.getAnswer().getQuestion());
		dataCatalog.getPhoneListByTypeId(this.userForm.getPhoneContact().getPhoneList());
		
		
		
		//System.out.println(session.get("usersListSearch"));
		//System.out.println(session.get("userSearchResult"));
		if(session.get(Constants.USER_SEARCH_RESULT)!=null){
			userSelected=(User)session.get(Constants.USER_SEARCH_RESULT);
			
			int userId=userSelected.getUserId();
			//register=userSelected.getUserPrivilage().getUserPrivilage();
			userSelected=this.userForm.getUserClon();
			userSelected.setUserId(userId);
			System.out.println("User was clonned");
			
			//userSelected=updateUserSelectedSession(this.userForm, userSelected);
			
		}
		
		session.put(Constants.USER_SEARCH_RESULT, userSelected);
		System.out.println("Nos vamos a cargar imagenes!!!");
		System.out.println("Selected pictures will be uploaded. ");
		//Remove this part of code
		
		for(UserPrivilage userPrivilage: dataCatalog.getUserPrivilageList()){
			if(userPrivilage.getUserPrivilage().equalsIgnoreCase(register)){
				userSelected.getUserPrivilage().setUserPrivilage(userPrivilage.getUserPrivilage());
				userSelected.getUserPrivilage().setUserPrivilageId(userPrivilage.getUserPrivilageId());
			}
		}
		
		if(sessionType.equalsIgnoreCase(Constants.FOREIGN_USER)){
			return Constants.SUCCESS_REGISTER_FOREIGN;
		}else if (true){
			return SUCCESS;
		}
		
		
		try {

			// Review this piece of code!!!!
			System.out.println("\n\n upload1");
			System.out.println("files:");
			for (File u : upload) {
				System.out.println("*** " + u + "\t" + u.length());
			}
			System.out.println("filenames:");
			for (String n : uploadFileName) {
				System.out.println("*** " + n);
			}
			System.out.println("content types:");
			if (uploadContentType.size() > 0) {

				for (int i = 0; i < uploadContentType.size(); i++) {

					String c = uploadContentType.get(i);

					System.out.println("*** " + c);

					

				}
				String filePath = servletRequest.getSession()
						.getServletContext().getRealPath("/");
				System.out.println("Server path:" + filePath);

				List<File> renamedFilesList=new ArrayList<File>();
				File fileToCreate;
				
				for (int i=0;i<this.upload.size();i++){
					String fileName = this.upload.get(i).getName();
					
					fileName=FormatUtility.renameFullFileName(fileName, "Test_File_0000000"+i, "jpg");
					fileToCreate= new File(filePath, fileName);
					FileUtils.copyFile(this.upload.get(i), fileToCreate);
					renamedFilesList.add(fileToCreate);
					
				}
				
				
				//String fileName = this.uploads.get(i).getName()
					//	.replaceAll("\\.tmp$", ".jpg");

				//File fileToCreate = new File(filePath, fileName);

				//TransferFileFTP transferFileFTP = new TransferFileFTP("ftp.260mb.com","pacus_3798589","860523",21,"/htdocs/images/testFTPjava");
				TransferFileFTP transferFileFTP = new TransferFileFTP("127.0.0.1","luis","luis",21,null);
				transferFileFTP.setFileType(transferFileFTP.BINARY_FILE_TYPE);
				
				System.out.println(transferFileFTP.sendFile(renamedFilesList));
				
				
				session.put("uploadFileName", uploadFileName);
				
				for(String uploadFileNameString:uploadFileName){
					System.out.println(uploadFileNameString);
				}
				
				return "success";
			}
			System.out.println("\n\n");

		} catch (Exception ex) {
			ex.printStackTrace();
			addActionError(ex.getMessage());

			return INPUT;
		}
		

		return INPUT;
	} 
	
	public String addUserRegister() {
		
		if(!SessionValidator.isValidSession(session)){
			return SessionValidator.INVALID_SESSION;
		}
		
		String sessionType=(String)session.get(Constants.SESSION_TYPE);
		
		boolean result=false;
		
		User userSelected=(User)session.get(Constants.USER_SEARCH_RESULT);

		if(userSelected.getUserId()>0){
			System.out.println("User selected " + userSelected.getUserId() + ", will be updated in Database");
			result=UserDAO.updateUserByUser(userSelected);
		}else{
			System.out.println("A new user will be added in Database ->" +userSelected.getUserId() +" : "+userSelected.getUser() + " - " + userSelected.getEmail());
			result=UserDAO.insertNewUser(userSelected);
		}

		if(result){
			System.out.println("User has been register/updated correctly!!!");
			if(sessionType.equalsIgnoreCase(Constants.FOREIGN_USER)){
				return Constants.SUCCESS_REGISTER_FOREIGN;
			}else{
				return SUCCESS;
			}
		}else{
			return ERROR;
		}

	}
	

	public Map getSession() {
		return session;
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public List<File> getUpload() {
		return upload;
	}

	public void setUpload(List<File> upload) {
		this.upload = upload;
	}

	public List<String> getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(List<String> uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public List<String> getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(List<String> uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}

	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}

	public User getUserForm() {
		return userForm;
	}

	public void setUserForm(User userForm) {
		this.userForm = userForm;
	}

	public String getRegister() {
		return register;
	}

	public void setRegister(String register) {
		this.register = register;
	}
	
	
}
